<template>
  <div class="file-upload">
    <el-upload
      action
      class="file-upload-upload"
      ref="file_upload"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      :http-request="upload"
      :on-remove="handleUploadRemove"
      :on-error="handleUploadError"
      :before-remove="beforeRemove"
      :on-preview="handleUploadPreview"
      :on-exceed="handleUploadExceed"
      :file-list="curFileList"
      :limit="limit">
      <el-button type="primary" icon="el-icon-plus" size="small">添加</el-button>
      <!-- <button><el-link :underline="false" icon="el-icon-plus">添加</el-link></button> -->
    </el-upload>
    <el-link class="down" :underline="false" v-if="needDownload" @click="downloadHandle">模板下载</el-link>
  </div>
</template>
<script>
import { ALERT } from '@/utils/responseHandle'
import { COMMON } from '@/utils/commonUtil'
import fileapi from '@/api/fileapi'
import * as Constant from '@/utils/constant'
export default {
  /**
   * 文件上传组件
   */
  name: 'FileUploadCommon',
  props: {
    limit: { // 最大允许上传个数
      type: Number,
      default: 1000
    },
    fileTypes: { // 允许上传文件类型
      type: Array,
      default: () => {return [
        'doc','docx','mp3','pdf','ppt','pptx','txt','wps','xlsx','rar','zip','jpg'
      ]}
    },
    fileKey:{//字段名，用于区分多个上传
      type:String,
      default:"",
    },
    fileList: {// 附件列表
      type: Array,
      default: () => {return []}
    },
    reset: { // 编辑回显 刷新curFileList
      type: Boolean,
      type: false
    },
    //是否需要模板下载
    needDownload: {
      type: Boolean,
      default: false
    },
    
    //模板下载地址
    downloadUrl:String,
  },
  data () {
    return {
      curFileList: this.fileList // 附件列表
    }
  },
  computed: {
  },
  mounted () {
  },
  methods: {
    upload (fileObj) {
      // this.uploadFile({ fileObj: fileObj }) // 文件上传接口
      fileapi.uploadFile(fileObj, response => {
        let res = response || {};
        let resData = res.data || {};
        if (resData.code === Constant.RT_SUCCESS) {
          fileObj.onProgress({ percent: 100 })
          setTimeout(() => {
            fileObj.onSuccess(resData, fileObj)
          }, 200)
        } else {
          // ALERT.errorDefault(res.msg)
          this.$message.error(resData.msg)
          fileObj.onError(resData, fileObj)
        }
      })
    },
    handleUploadExceed () { // 限制上传个数回调
      ALERT.warn(`最多只能上传${this.limit}个附件！`)
      return false
    },
    beforeUpload (file) {
      let filetype = file.name.split('.').pop()
      // let fileTypes = ['pdf', 'txt', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'zip', 'rar', 'jpeg', 'png', 'jpg', 'iso']
      if (this.fileTypes.length === 0) return true
      if (this.fileTypes.indexOf(filetype) === -1) {
        this.$message.warning(`附件上传只能是${this.fileTypes}格式!`)
        return false
      }
      return true
    },
    handleUploadSuccess (res, option) { // res： 后台返回对象，option： 文件对象
      this.$emit("uploadSuccess",res.data,this.fileKey)
    },
    beforeRemove (file, fileList) {
    },
    handleUploadError(){ 
      this.$emit("uploadFail")
    },
    handleUploadRemove (file, fileList) {
      this.$emit('uploadRemove', fileList ,this.fileKey)
    },
    handleUploadPreview (file) {
      COMMON.downloadLinkByUrl(file.url, file.name)
    },
    // 清空附件文件列表
    clearFiles () {
      this.$refs['file_upload'].clearFiles()
      this.curFileList = []
    },
    setUploadOssFileListItemNameTitle (fileName) { // 设置文件名 dom title
      setTimeout(() => {
        let fileListItemName = document.querySelectorAll('.cata-upload-oss .el-upload-list__item-name')
        fileListItemName[0].title = fileName
      }, 100)
    },
    //下载模板
    downloadHandle(){
      window.open(this.downloadUrl)
    }
  },
  watch: {
    fileList: {
      immediate: true,
      handler () {
        this.curFileList = JSON.parse(JSON.stringify(this.fileList))
        // if (this.flag && this.fileList.length > 0) {
        //   this.flag = false
        //   this.curFileList = JSON.parse(JSON.stringify(this.fileList))
        // }
      }
    }
  }
}
</script>
<style lang="scss">
.file-upload {
  margin-top: 0 !important;
  position: relative;
  .down{
    position: absolute;
    left:100px;
    top: 0;
    &.el-link.el-link--default{
      color: #004a86;
    }
  }
  &-label {
    color: #004a86;
  }
}
</style>
